<template>
  <div>
    <el-row type="flex" justify="end" class="button-save">
      <el-button type="primary" @click="save">保存</el-button>
    </el-row>
    <el-form
      :model="directionOfTriage"
      label-position="right"
      label-width="120px"
      size="small"
    >
      <!-- <el-form-item label="科内"> -->
      <el-form-item label="科室">
        <el-radio-group v-model="directionOfTriage.dept" @change="selectDept">
          <el-radio
            v-for="(item, index) in departmentList"
            :key="index"
            :label="item.name"
          >
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- <el-form-item v-if="userList.length > 0" label="科外"> -->
      <el-form-item v-if="userList.length > 0" label="医生">
        <el-radio-group v-model="directionOfTriage.user" @change="selectUser">
          <el-radio
            v-for="(item, index) in userList"
            :key="index"
            :label="item.id"
          >
            {{ item.name }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import {
  getDepartmentList,
  getUserListWeb,
  sendMessageDirectHandover
} from '@/api/triage/triage-new'

export default {
  name: 'TriageDirection',
  props: {
    id: {
      type: Object,
      default: () => {}
    }
  },
  data() {
    return {
      directionOfTriage: {},
      departmentList: [],
      userList: [],
      selectDoc: {}
    }
  },
  created() {
    this.getDepartmentList()
  },
  methods: {
    selectDept(val) {
      getUserListWeb({
        departmentNameStr: val,
        dispatchId: this.id.dispatchId
      }).then((res) => {
        if (res.code == 0) {
          this.userList = res.data
        }
      })
    },
    selectUser(val) {
      for (let i = 0; i < this.userList.length; i++) {
        const el = this.userList[i]
        if (el.id == val) {
          this.selectDoc = el
          break
        }
      }
    },
    getDepartmentList() {
      getDepartmentList({
        hospitalId: this.$store.getters.hospitalId
      }).then((res) => {
        if (res.code == 0) {
          this.departmentList = res.data
        }
      })
    },
    save(obj) {
      if (this.selectDoc.api_token) {
        sendMessageDirectHandover({
          medicalId: this.id.medicalId,
          dispatchId: this.id.dispatchId,
          toUserId: this.selectDoc.id,
          apiToken: this.selectDoc.api_token
        }).then((res) => {
          if (res.code == 0) {
            this.$message.success('保存成功')
            this.directionOfTriage = {}
            this.selectDoc = {}
            this.userList = []
          } else {
            this.$message.error('保存失败')
          }
        })
      } else {
        this.$message.error('请选择科室医生')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.button-save {
  padding-right: 40px;
  margin-bottom: 20px;
}
</style>
